package com.makenv.web.backend;

import com.makenv.domain.Url;
import com.makenv.service.UrlService;
import com.makenv.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/manage/index")
public class IndexManageController {

    @Autowired
    UrlService urlService;

    //从配置文件中读取的每次显示的行数
    private int row;

    @RequestMapping("/showback")
    public String showBack(HttpServletRequest request) {
        forShow(request);
        return "back/link";
    }

    @RequestMapping("/delete")
    public String delete(@RequestParam String jsonStr) {
        String[] idArray = jsonStr.split(",");
        for (String str : idArray) {
            int i = Integer.valueOf(str);
            urlService.deleteByPrimaryKey(i);
        }

        //这个请求是由ajax发送上来的，SpringMVC不会进行页面的跳转，用ajax进行跳转
        return "";
    }

    @RequestMapping("/add")
    public String add(@RequestParam String url, @RequestParam String description, @RequestParam int priority) {
        urlService.insert(url, description, priority);
        return "redirect:/manage/index/showback";
    }

    @RequestMapping("/jumpback")
    public String jumpback(@RequestParam int pageNum, HttpServletRequest request) {
        int pageSum = getPageSum();
        request.getSession().setAttribute("pageSum", pageSum);
        request.getSession().setAttribute("pageNum", pageNum);
        List<Url> urlList = urlService.showUrlList((pageNum - 1) * row, row);
        request.setAttribute("urlList", urlList);
        return "back/link";
    }

    @RequestMapping("/update")
    public String update(@RequestParam int id, @RequestParam String url, @RequestParam String description, @RequestParam int priority) {
        urlService.updateByPrimaryKey(id, url, description, priority);
        return "redirect:/manage/index/showback";
    }

    public void forShow(HttpServletRequest request) {
        row = Config.getInt("showRow");
        List<Url> urlList = urlService.showUrlList(0, row);
        int pageSum = getPageSum();
        request.getSession().setAttribute("pageSum", pageSum);
        request.getSession().setAttribute("pageNum", 1);

        request.setAttribute("urlList", urlList);
    }

    public Integer getPageSum() {
        int pageSum;
        int totalUrl = urlService.getUrlsum();
        if (totalUrl % row == 0) {
            pageSum = totalUrl / row;
        } else {
            pageSum = totalUrl / row + 1;
        }
        return pageSum;
    }
}